package main;

import java.awt.Dimension;
import javax.swing.JScrollPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

/**
 * 
 * @author Balazs Pete
 *
 */
public class LineNumber extends JScrollPane {
	static private TextArea panel = null;
	private int width, height;
	
	public LineNumber(int width, int height){
		super();
		this.width = width;
		this.height = height;
		setViewportView(getPanel(width, height));
		panel.setEditable(false);
	}
	
	/**
	 * Method to get the panel
	 * @param width width of panel
	 * @param height height of panel
	 * @return line number panel
	 * @author Balazs Pete
	 * @throws BadLocationException 
	 */
	private TextArea getPanel(int width, int height){
		if(panel==null){
			panel = new TextArea(width,height);
			panel.setBounds(0,-5,width,height*2);
			try {
				addNumbers(1,null);
			} catch (BadLocationException e) {
				System.out.println("BadLocationException in method LineNumber.getPanel()");
			}
			Dimension d = new Dimension(this.getVerticalScrollBar().getSize().width,this.getVerticalScrollBar().getSize().height);
			this.getVerticalScrollBar().setPreferredSize(d);
			this.getVerticalScrollBar().setModel(main.MainWindow.getJScrollPaneVerticalScrollBar().getModel());
		}
		return panel;
	}

	/**
	 * Method to add the numbers to the panel
	 * @param lines number of active lines
	 * @author Balazs Pete
	 * @throws BadLocationException 
	 */
	private void addNumbers(int lines,errors.ErrorOnLine e) throws BadLocationException{
		int i=0,j=3;

		Document doc = null;
		doc = panel.getDocument();
		doc.remove(0, doc.getLength());
		
		if(e!=null){//e!=null
			j = e.getLine();
		}
		while (i<lines){
			if(i<9){
				doc.insertString(doc.getLength(), "    "+(i+1)+"\n", null);
			} else if (i<99){
				doc.insertString(doc.getLength(), "  "+(i+1)+"\n", null);
			} else {
				doc.insertString(doc.getLength(), (i+1)+"\n", null);
			}
			i++;
		}
		new errors.RandomError(i);
		panel.setText(doc.getText(0, doc.getLength()-1));
		
	}
	
	/**
	 * Method to update the line numbering
	 * @param lines number of active lines
	 * @author Balazs Pete
	 * @throws BadLocationException 
	 */
	public void updateNumbers(int lines){
		panel.setText("");
		try {
			addNumbers(lines,null);
		} catch (BadLocationException e) {
			System.out.println("BadLocationException in method LineNumber.updateNumber()");
		}
	}
}
